package com.baosight.risk.web.xtzy;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baosight.iplat4j.core.web.threadlocal.UserSession;
import com.baosight.risk.api.xtzy.IXtzyCompanyService;
import com.baosight.risk.base.controller.BaseController;
import com.baosight.risk.common.annotation.Log;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.enums.BusinessType;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.common.utils.ShiroUtils;
import com.baosight.risk.service.quartz.entity.SyncOrgEntitiy;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyUser;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 类 名: XtzyCompanyController
 * 描 述: 组织机构
 * 作 者: 黎秋荣
 * 创 建：2019年04月25日
 * 历 史: (版本) 作者 时间 注释
 */
@Slf4j
@RestController
@RequestMapping("/xtzy/company")
@Api(value = "组织机构", description = "组织机构", produces = MediaType.APPLICATION_JSON)
public class XtzyCompanyController extends BaseController {

    @Autowired
    private IXtzyCompanyService companyService;



    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @GetMapping("edit")
    @ApiOperation("根据ID查询")
    public AjaxResult edit(@RequestParam("id") String id) {
        XtzyCompany company = companyService.get(id);
        XtzyCompany parentCompany = companyService.get(company.getParentGuid());
        if (parentCompany != null) {
            company.setExt2(parentCompany.getCompName());
        }
        return success(company);
    }

    /**
     * 查询组织机构信息（根据用户判断）
     *
     * @param company
     * @return
     */
    @RequestMapping("list")
    @ApiOperation("根据组织编码查询一级组织机构信息")
    public AjaxResult list(@RequestBody XtzyCompany company) {
        log.info("查询组织机构信息：" + company.toString());
        return getResultPage(companyService.selectCompany(company, getUser()));
    }

    /**
     * 查询组织机构信息（全部数据）
     *
     * @param company
     * @return
     */
    @PostMapping("allList")
    @ApiOperation("根据组织编码查询一级组织机构信息")
    public AjaxResult allList(@RequestBody XtzyCompany company) {
        log.info("查询组织机构信息：" + company.toString());
        if (company.getExt1() != null && company.getExt1().equals("Y")) {

            company.setPathCode(company.getCompCode() == null ? null : company.getCompCode());
            company.setPathName(company.getCompName() == null ? null : company.getCompName());
            company.setCompCode(null);
            company.setCompName(null);
        }
        List<XtzyCompany> result = companyService.selectAllCompany(company);

        //判断是否将查询结果更改为平列表
        if (company.getCompCode() != null || company.getCompName() != null || company.getPathCode() != null || company.getPathName() != null) {
            result.stream().forEach(m -> m.setParentGuid("0"));
        }
        return getResultPage(result);
    }

    /**
     * 查看本单位，及其上级、及其下属
     *
     * @param company
     * @return
     */
    @PostMapping("ownerCompList")
    @ApiOperation("查看本单位，及其上级、及其下属")
    public AjaxResult ownerCompList() {
    	String compCode = ShiroUtils.getUser().getManageCompCode();
        return success(companyService.ownerCompList(compCode));
    }

    /**
     * 查询外部数据库组织机构信息（全部数据）
     *
     * @param syncOrgEntitiy
     * @return
     */
    @GetMapping("allListFromOtherDB")
    @ApiOperation("查询外部数据库组织机构信息（全部数据）")
    public AjaxResult allListFromOtherDB(SyncOrgEntitiy syncOrgEntitiy) {
        log.info("查询组织机构信息：" + syncOrgEntitiy.toString());
        startPage();
        List<SyncOrgEntitiy> result = companyService.getAllOrgFromOtherDB(syncOrgEntitiy);
        return getResultPage(result);
    }

    /**
     * 根据组织编码查询一级组织机构信息
     *
     * @param companyCode
     * @return
     */
    @PostMapping("getOneLevelCompany")
    @ApiOperation("根据组织编码查询一级组织机构信息")
    public AjaxResult getOneLevelCompany(String companyCode) {
        log.info("根据组织编码查询一级组织机构信息：" + companyCode);
        return getResultPage(companyService.getOneLevelCompany(companyCode));
    }

    /**
     * 根据组织编码查询一级组织机构信息
     *
     * @param companyCode
     * @return
     */
    @PostMapping("getParantAndChildrens")
    @ApiOperation("根据组织编码查询一级组织机构信息及下级部门")
    public AjaxResult getParantAndChildrens(String companyCode) {
        log.info("根据组织编码查询一级组织机构信息及下级部门：" + companyCode);
        return getResultPage(companyService.getParantAndChildrens(companyCode));
    }

    /**
     * 根据公司层级和角色查询组织机构信息及所属人员
     *
     * @param pathLevel 公司层级
     * @param roleId    角色ID
     * @param userFalg  0=查询所有；1=代查询当前登陆人下一级子公司所有人
     * @return
     */
    @PostMapping("getCompanyAndUsers")
    @ApiOperation("根据公司层级和角色查询组织机构信息及所属人员")
    public AjaxResult getCompanyAndUsers(String pathLevel, String roleId, Integer userFalg) {
        log.info("查询组织机构信息：" + pathLevel + "======" + roleId);
        return getResultPage(companyService.getCompanyAndUsers(pathLevel, roleId, userFalg, getUser()));
    }

    /**
     * 查找参加风险自评的公司及风险管理员
     *
     * @return
     */
    @PostMapping("getRiskCompany")
    @ApiOperation("查找参加风险自评的公司及风险管理员")
    public AjaxResult getRiskCompany() {
        return getResultPage(companyService.getRiskCompany());
    }

    /**
     * 本单位及下级组织所有人 (如果有下级)
     *
     * @param compId 公司ID
     * @param roleId 角色ID
     * @return
     */
    @PostMapping("getNextComp")
    @ApiOperation("本单位及下级组织所有人 (如果有下级)")
    public AjaxResult getNextComp(String compId, String roleId) {
        log.info("查询组织机构信息：" + compId + "======角色：" + roleId);
        return getResultPage(companyService.getNextComp(compId, roleId));
    }

    /**
     * 根据单位和角色获取一级子公司下的所有人
     *
     * @param compId 公司ID
     * @param roleId 角色ID
     * @return
     */
    @PostMapping("getParentComp")
    @ApiOperation("根据单位和角色获取一级子公司下的所有人")
    public AjaxResult getParentComp(String compId, String roleId) {
        log.info("查询组织机构信息：" + compId + "======角色：" + roleId);
        return success(companyService.getParentComp(compId, roleId));
    }

    /**
     * 根据公司和角色查询用户
     *
     * @param compId 公司ID
     * @param roleId 角色ID
     * @return
     */
    @PostMapping("getUserAndCompIdAndRoleId")
    @ApiOperation("根据公司和角色查询用户")
    public AjaxResult getUserAndCompIdAndRoleId(String compId, String roleId) {
        log.info("查询组织机构信息：" + compId + "======" + roleId);
        return getResultPage(companyService.getUserAndCompIdAndRoleId(compId, roleId));
    }

    /**
     * 根据用户查找组织
     *
     * @return
     */
    @GetMapping("getCompany")
    public AjaxResult getCompany(HttpServletRequest request) {
        UserSession.web2Service(request);
        String userName = UserSession.getLoginName();
        List<XtzyCompany> list = companyService.getCompany(userName);
        UsernamePasswordToken token = new UsernamePasswordToken(userName, userName);
        SecurityUtils.getSubject().login(token);
        return getResultPage(list);
    }
    @PostMapping("getCompany")
    public AjaxResult getCompany1(HttpServletRequest request) {
        UserSession.web2Service(request);
        String userName = UserSession.getLoginName();
        List<XtzyCompany> list = companyService.getCompany(userName);
        UsernamePasswordToken token = new UsernamePasswordToken(userName, userName);
        SecurityUtils.getSubject().login(token);
        return getResultPage(list);
    }

    /**
     * 根据当前登录人获取公司
     *
     * @return
     */
    @GetMapping("getTop1CompanyByUser")
    public AjaxResult getTop1CompanyByUser() {
        XtzyUser user = getUser();
        String compCode = user.getExt1();
        return success(companyService.getTop1CompanyByUser(compCode));
    }


    @GetMapping("getCompany2")
    public AjaxResult getCompany2(String userCode) {
        List<XtzyCompany> list = companyService.getCompany(userCode);
        return getResultPage(list);
    }


    /**
     * 保存组织机构信息
     *
     * @param company
     * @return
     */
    @PostMapping("save")
    @Log(title = "保存组织机构信息")
    @ApiOperation("保存组织机构信息")
    @RequiresPermissions("xtzy:company:save")
    public AjaxResult save(@RequestBody XtzyCompany company) {
        company = (XtzyCompany) BeanUtils.initBean(company);
        company.setId(company.getCompCode());

        company.setStatus("10");
        company.setEndLevelFlag((short)1);
        //添加节点路径相关信息
        String parentGuid = company.getParentGuid();
        if (!"".equals(parentGuid)) {
            XtzyCompany parentCompany = companyService.get(parentGuid);
            String path = parentCompany.getPathName() + "/" + company.getCompName();
            String pathCode = parentCompany.getPathCode() + "/" + company.getCompCode();
            int pathLevel = parentCompany.getPathLevel() + 1;

            if (parentCompany.getEndLevelFlag() == 1) {
                parentCompany.setEndLevelFlag((short)0);
                companyService.update(parentCompany);
            }

            company.setPathName(path);
            company.setPathCode(pathCode);
            company.setPathLevel((short) pathLevel);
        }
        log.info("保存组织机构参数：" + company.toString());
        return toAjax(companyService.insert(company));
    }

    /**
     * 修改组织机构信息
     *
     * @param company 组织机构信息
     * @return
     */
    @PostMapping("update")
    @Log(title = "修改组织机构信息", businessType = BusinessType.UPDATE)
    @RequiresPermissions("xtzy:company:update")
    @ApiOperation("修改组织机构信息")
    public AjaxResult update(@RequestBody XtzyCompany company) throws Exception {
        return toAjax(companyService.updateCompany(company));
    }

    /**
     * 禁用组织机构
     *
     * @param id 组织机构ID
     * @return
     */
    @PostMapping("delete")
    @Log(title = "禁用组织机构", businessType = BusinessType.DELETE)
    @RequiresPermissions("xtzy:company:delete")
    @ApiOperation("禁用组织机构")
    public AjaxResult delete(@RequestBody String id) {
        return toAjax(companyService.deleteById(id));
    }

    @PostMapping("updateStatus")
    @Log(title = "更新组织机构状态", businessType = BusinessType.UPDATE)
    @RequiresPermissions("xtzy:company:updatestatus")
    @ApiOperation("更新组织机构状态")
    public AjaxResult updateStatus(@RequestBody XtzyCompany company) {
        // 检索当前公司下全部子公司部门信息
        List<XtzyCompany> companyList = companyService.selectAllSubsetByParentID(company.getId());

        List<String> idList = new ArrayList<>();
        for (XtzyCompany xtzyCompany : companyList) {
            idList.add(xtzyCompany.getId());
        }

        return toAjax(companyService.updateCompanyStatus(idList, company.getStatus()));
    }

    @PostMapping("updateRiskFlag")
    @Log(title = "更新组织风险识别标识", businessType = BusinessType.UPDATE)
    @RequiresPermissions("xtzy:company:updateriskflag")
    @ApiOperation("更新组织风险识别标识")
    public AjaxResult updateRiskFlag(@RequestBody XtzyCompany company) {
        String riskFlag = company.getRiskFlag();
        company = companyService.get(company.getId());
        company = (XtzyCompany) BeanUtils.updateBean(company);
        company.setRiskFlag(riskFlag);
        log.info("修改组织机构信息：" + company.toString());
        return toAjax(companyService.update(company));
    }

    @PostMapping("updateManageFlag")
    @Log(title = "更新管理单位标识", businessType = BusinessType.UPDATE)
    @RequiresPermissions("xtzy:company:updatemanageflag")
    @ApiOperation("更新管理单位标识")
    public AjaxResult updateManageFlag(@RequestBody XtzyCompany company) {
        String manageFlag = company.getManageFlag();
        company = companyService.get(company.getId());
        company = (XtzyCompany) BeanUtils.updateBean(company);
        company.setManageFlag(manageFlag);
        log.info("修改组织机构信息：" + company.toString());
        return toAjax(companyService.update(company));
    }

    /**
     * 对组织order进行重排序,更新路径信息和OrderId
     *
     * @return
     */
    @GetMapping("sortCompany")
    public AjaxResult sortCompany(HttpServletRequest request) {
        companyService.updateSortCompany();
        return success("排序完成");
    }

    /**
     * 查询一级子公司及部门
     *
     * @param compCode  当前所在组织
     * @param pathLevel 层级
     */
    @GetMapping("getTop")
    @ApiOperation("查询一级子公司及部门")
    public AjaxResult getTopCompany(String compCode, Short pathLevel) {
        return AjaxResult.success("查询成功", companyService.getTopCompany(compCode, pathLevel));
    }

    /**
     * 查询当前组织下某种角色的用户
     *
     * @param compCode
     * @param roleCode
     * @return
     */
    @GetMapping("getUserByCompAndRole")
    @ApiOperation("查询当前组织下某种角色的用户")
    public AjaxResult getUserByCompAndRole(@RequestParam("compCode") String compCode, @RequestParam("roleCode") String roleCode) {
        return AjaxResult.success("查询成功", companyService.getUserByCompAndRole(compCode, roleCode));
    }

    /**
     * 生成EHR的组织树
     *
     */
    @GetMapping("ehrTree")
    @ApiOperation("生成EHR的组织树")
    public AjaxResult getEHRTree(String type) {
        return AjaxResult.success("查询成功", companyService.selectOrgTree(type));
    }

    /**
     * 删除组织机构
     *
     */
    @GetMapping("deleteCompany")
    @Log(title = "删除组织机构", businessType = BusinessType.DELETE)
    @RequiresPermissions("xtzy:company:delete")
    @ApiOperation("删除组织机构")
    public AjaxResult deleteCompany(@RequestParam("id") String id) {
        return toAjax(companyService.delete(id));
    }

}
